package cn.zyjblogs.sms.provider;


import cn.zyjblogs.sms.common.SmsRequest;
import cn.zyjblogs.sms.provider.baidu.BaiduBceSmsHandleGranter;
import cn.zyjblogs.sms.task.constant.ProviderType;
import cn.zyjblogs.sms.task.constant.TaskStatus;
import cn.zyjblogs.sms.task.dto.TaskResultDTO;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author zhuyijun
 */
public class CompositeSmsGranter implements SmsGranter {
    private final List<SmsGranter> smsGranters;

    public CompositeSmsGranter(List<SmsGranter> smsGranters) {
        this.smsGranters = new ArrayList<>(smsGranters);
    }

    @Override
    public SmsGranter getGranter(ProviderType providerType) {
        for (SmsGranter granter : smsGranters) {
            SmsGranter granters = granter.getGranter(providerType);
            if (granters != null) {
                return granters;
            }
        }
        return null;
    }

    @Override
    public TaskResultDTO sendSms(ProviderType providerType, SmsRequest smsRequest) {
        SmsGranter granter1 = getGranter(providerType);
        if (granter1 != null) {
            return granter1.sendSms(providerType, smsRequest);
        }
        return new TaskResultDTO(new LinkedList<>(), TaskStatus.FAIL);
    }


    public void addTokenGranter(SmsGranter smsGranter) {
        if (smsGranter == null) {
            throw new IllegalArgumentException("sms granter is null");
        }
        smsGranters.add(smsGranter);
    }
}
